package com.arvinclub.web.controller.other;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 下载文件（暂时没用到）
 */
@Controller
public class DownloadController
{
    @GetMapping("download")
    public String download(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String file_name = request.getParameter("name");
        String filepath = "/arvin/" + file_name;
        //String ext = file_path.substring(file_path.lastIndexOf(".")+1);
        //这里获取服务器的绝对路径。如果不会用的话，用下面注释掉的方法就可以
        //String root = getServletContext().getRealPath("/");
        //用下面的方法前，需要把HttpServletRequest request当做一个参数传递到本方法中，直接使用即可
        //String root = request.getSession().getServletContext().getRealPath("/");

        //file_name=file_name+"."+ext; //如果文件名中有后缀 如.zip .jpg等  就不用这句话
        //String filepath=file_path;
        File file = new File(filepath);
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(file_name.getBytes(), "utf-8"));
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        response.setContentType("application/octet-stream");
        //这里的addHeader方法，如果报错，请使用下方注释掉的方法。
        //response.addHeader("Content-Length", file.length());
        //把第二个参数更改为String 类型即可
        response.addHeader("Content-Length", String.valueOf(file.length()));
        return null;
    }
}
